<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>背点八股文</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
    <style>
        .container-fluid {
            padding: 20px;
        }
        .card {
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .card-header {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .table th {
            background-color: #f8f9fa;
        }
        .pagination {
            margin-top: 20px;
        }
        .btn-group {
            margin: 5px;
        }
        textarea {
            resize: vertical;
            min-height: 100px;
        }
        #toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
        .favorite-star {
            color: #ffc107;
            cursor: pointer;
        }
        .favorite-star.far {
            color: #6c757d;
        }
        .nav-tabs {
            margin-bottom: 20px;
        }
        #sidebar {
            min-height: calc(100vh - 56px);
            background-color: #f8f9fa;
            border-right: 1px solid #dee2e6;
            padding: 20px 0;
        }
        #sidebar .nav-link {
            color: #495057;
            border-radius: 0;
        }
        #sidebar .nav-link:hover {
            background-color: #e9ecef;
        }
        #sidebar .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .type-badge {
            margin: 5px;
            cursor: pointer;
        }
        .user-info {
            margin-right: 15px;
        }
        .search-card {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">背点八股文</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="showFavoritesBtn">我的收藏</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="showAllBaguwenBtn">所有八股文</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <span id="currentUserNickname">用户</span>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
                            <a class="dropdown-item" href="#" id="logoutBtn">退出登录</a>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div id="toast"></div>
        
        <div class="row" id="mainContent">
            <!-- 左侧边栏 -->
            <div class="col-md-2" id="sidebar">
                <h5 class="pl-3 mb-3">八股文类型</h5>
                <div class="nav flex-column nav-pills" id="typeList">
                    <a class="nav-link active" href="#" data-type="all">所有类型</a>
                    <!-- 动态生成类型列表 -->
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10">
                <!-- 搜索区域 -->
                <div class="card search-card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <form id="searchForm" class="form-inline">
                                    <div class="input-group flex-grow-1 mr-2">
                                        <input type="text" class="form-control" id="searchKeyword" placeholder="搜索八股文...">
                                        <div class="input-group-append">
                                            <button class="btn btn-outline-primary" type="submit">搜索</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            <div class="col-md-4 text-right">
                                <button class="btn btn-primary" id="addBaguwenBtn">
                                    <i class="fas fa-plus"></i> 添加八股文
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 八股文列表 -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span id="listTitle">八股文列表</span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>类型</th>
                                        <th>问题</th>
                                        <th>内容</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="baguwenList">
                                    <!-- 动态生成内容 -->
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <span>总记录数: <span id="totalCount">0</span></span>
                            </div>
                            <div>
                                <ul class="pagination" id="pagination">
                                    <!-- 动态生成分页 -->
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 收藏夹内容 -->
        <div class="row d-none" id="favoriteContent">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">我的收藏</div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>类型</th>
                                        <th>问题</th>
                                        <th>内容</th>
                                        <th>备注</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="favoriteList">
                                    <!-- 动态生成内容 -->
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <span>总收藏数: <span id="totalFavoriteCount">0</span></span>
                            </div>
                            <div>
                                <ul class="pagination" id="favoritePagination">
                                    <!-- 动态生成分页 -->
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加八股文模态框 -->
    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModalLabel">添加八股文</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addForm">
                        <div class="form-group">
                            <label for="type">类型</label>
                            <input type="text" class="form-control" id="type" name="type" required>
                        </div>
                        <div class="form-group">
                            <label for="question">问题</label>
                            <input type="text" class="form-control" id="question" name="question" required>
                        </div>
                        <div class="form-group">
                            <label for="content">内容</label>
                            <textarea class="form-control" id="content" name="content" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveAdd">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">编辑八股文</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <input type="hidden" id="editId">
                        <div class="form-group">
                            <label for="editType">类型</label>
                            <input type="text" class="form-control" id="editType" name="editType" required>
                        </div>
                        <div class="form-group">
                            <label for="editQuestion">问题</label>
                            <input type="text" class="form-control" id="editQuestion" name="editQuestion" required>
                        </div>
                        <div class="form-group">
                            <label for="editContent">内容</label>
                            <textarea class="form-control" id="editContent" name="editContent" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveEdit">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" aria-labelledby="detailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="detailModalLabel">八股文详情</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span id="detailType">类型</span>
                            <i class="far fa-star favorite-star" id="detailFavoriteStar" data-id=""></i>
                        </div>
                        <div class="card-body">
                            <h5 class="card-title" id="detailQuestion">问题</h5>
                            <p class="card-text" id="detailContent">内容</p>
                            <div class="text-muted">
                                <small>创建时间: <span id="detailCreateTime"></span></small><br>
                                <small>更新时间: <span id="detailUpdateTime"></span></small>
                            </div>
                            
                            <!-- 收藏备注区域 -->
                            <div id="favoriteRemarkArea" class="mt-3 d-none">
                                <hr>
                                <h6>收藏备注:</h6>
                                <p id="favoriteRemark" class="font-italic">暂无备注</p>
                                <button class="btn btn-sm btn-outline-primary" id="editRemarkBtn">编辑备注</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 收藏模态框 -->
    <div class="modal fade" id="favoriteModal" tabindex="-1" aria-labelledby="favoriteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="favoriteModalLabel">添加收藏</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="favoriteForm">
                        <input type="hidden" id="favoriteId">
                        <input type="hidden" id="favoriteBaguwenId">
                        <div class="form-group">
                            <label for="favoriteRemarkInput">备注</label>
                            <textarea class="form-control" id="favoriteRemarkInput" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveFavorite">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // 全局变量
        let currentPage = 1;
        const pageSize = 10;
        let currentSearchType = "all"; // all, keyword, type
        let currentSearchValue = "";
        // 收藏夹分页
        let currentFavoritePage = 1;
        let isFavoriteView = false;
        let currentFavorite = null;
        
        // 页面加载完成后执行
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();
            
            // 加载所有八股文
            loadBaguwen();
            
            // 加载八股文类型列表
            loadBaguwenTypes();
            
            // 添加八股文按钮点击
            $("#addBaguwenBtn").on("click", function() {
                // 清空表单
                $("#addForm")[0].reset();
                // 显示模态框
                $("#addModal").modal("show");
            });
            
            // 添加八股文表单提交
            $("#saveAdd").on("click", function() {
                addBaguwen();
            });
            
            // 编辑八股文保存
            $("#saveEdit").on("click", function() {
                updateBaguwen();
            });
            
            // 类型列表点击事件
            $(document).on("click", "#typeList .nav-link", function(e) {
                e.preventDefault();
                
                // 高亮选中的类型
                $("#typeList .nav-link").removeClass("active");
                $(this).addClass("active");
                
                const type = $(this).data("type");
                if (type === "all") {
                    // 显示所有八股文
                    currentSearchType = "all";
                    currentSearchValue = "";
                    currentPage = 1;
                    loadBaguwen();
                } else {
                    // 按类型搜索
                    currentSearchType = "type";
                    currentSearchValue = type;
                    currentPage = 1;
                    searchByType(type);
                }
            });
            
            // 关键字搜索
            $("#searchForm").on("submit", function(e) {
                e.preventDefault();
                const keyword = $("#searchKeyword").val().trim();
                if (keyword) {
                    currentSearchType = "keyword";
                    currentSearchValue = keyword;
                    currentPage = 1;
                    searchBaguwen(keyword);
                }
            });
            
            // 收藏按钮点击
            $(document).on("click", ".favorite-star", function() {
                const baguwenId = $(this).data("id");
                if ($(this).hasClass("fas")) {
                    // 已收藏，获取收藏信息
                    getFavoriteByBaguwenId(baguwenId, function(favorite) {
                        // 打开编辑备注模态框
                        $("#favoriteId").val(favorite.id);
                        $("#favoriteBaguwenId").val(baguwenId);
                        $("#favoriteRemarkInput").val(favorite.remark || "");
                        $("#favoriteModalLabel").text("编辑收藏备注");
                        $("#favoriteModal").modal("show");
                    });
                } else {
                    // 未收藏，打开收藏模态框
                    $("#favoriteId").val("");
                    $("#favoriteBaguwenId").val(baguwenId);
                    $("#favoriteRemarkInput").val("");
                    $("#favoriteModalLabel").text("添加收藏");
                    $("#favoriteModal").modal("show");
                }
            });
            
            // 保存收藏
            $("#saveFavorite").on("click", function() {
                const favoriteId = $("#favoriteId").val();
                const baguwenId = $("#favoriteBaguwenId").val();
                const remark = $("#favoriteRemarkInput").val();
                
                if (favoriteId) {
                    // 更新收藏备注
                    updateFavorite(favoriteId, baguwenId, remark);
                } else {
                    // 添加收藏
                    addFavorite(baguwenId, remark);
                }
            });
            
            // 显示收藏夹
            $("#showFavoritesBtn").on("click", function() {
                showFavorites();
            });
            
            // 显示所有八股文（从收藏夹返回）
            $("#showAllBaguwenBtn").on("click", function() {
                showAllBaguwen();
            });
            
            // 编辑备注按钮
            $("#editRemarkBtn").on("click", function() {
                if (currentFavorite) {
                    $("#favoriteId").val(currentFavorite.id);
                    $("#favoriteBaguwenId").val(currentFavorite.baguwenId);
                    $("#favoriteRemarkInput").val(currentFavorite.remark || "");
                    $("#favoriteModalLabel").text("编辑收藏备注");
                    $("#favoriteModal").modal("show");
                }
            });
            
            // 退出登录
            $("#logoutBtn").on("click", function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                localStorage.removeItem('nickname');
                localStorage.removeItem('userId');
                window.location.href = "./login.html";
            });
        });
        
        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const nickname = localStorage.getItem('nickname');
            
            if (!token) {
                window.location.href = "./login.html";
                return;
            }
            
            // 显示用户昵称
            $("#currentUserNickname").text(nickname || "用户");
            
            // 验证token有效性
            $.ajax({
                url: "/api/user/current",
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                error: function() {
                    // token无效，跳转到登录页
                    localStorage.removeItem('token');
                    localStorage.removeItem('username');
                    localStorage.removeItem('nickname');
                    localStorage.removeItem('userId');
                    window.location.href = "./login.html";
                }
            });
        }
        
        // 加载八股文类型列表
        function loadBaguwenTypes() {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: "/api/baguwen/types",
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        renderTypeList(response.data);
                    } else {
                        showToast("加载八股文类型失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("加载八股文类型失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 渲染类型列表
        function renderTypeList(types) {
            const typeList = $("#typeList");
            
            // 保留"所有类型"选项
            const allTypeLink = typeList.find("a[data-type='all']");
            typeList.empty();
            typeList.append(allTypeLink);
            
            // 添加各种类型
            types.forEach(function(type) {
                const typeLink = $(`<a class="nav-link" href="#" data-type="${type.type}">${type.type} <span class="badge badge-pill badge-secondary">${type.count}</span></a>`);
                typeList.append(typeLink);
            });
        }
        
        // 加载八股文列表
        function loadBaguwen() {
            isFavoriteView = false;
            $("#listTitle").text("八股文列表");
            
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/baguwen?pageNum=${currentPage}&pageSize=${pageSize}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        renderBaguwenList(response.data);
                    } else {
                        showToast("加载八股文失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("加载八股文失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 按关键字搜索八股文
        function searchBaguwen(keyword) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/baguwen/search?keyword=${encodeURIComponent(keyword)}&pageNum=${currentPage}&pageSize=${pageSize}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        renderBaguwenList(response.data);
                    } else {
                        showToast("搜索八股文失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("搜索八股文失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 按类型搜索八股文
        function searchByType(type) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/baguwen/type/${encodeURIComponent(type)}?pageNum=${currentPage}&pageSize=${pageSize}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        renderBaguwenList(response.data);
                    } else {
                        showToast("按类型搜索八股文失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("按类型搜索八股文失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 添加八股文
        function addBaguwen() {
            const baguwen = {
                type: $("#type").val(),
                question: $("#question").val(),
                content: $("#content").val()
            };
            
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: "/api/baguwen",
                type: "POST",
                headers: {
                    "Authorization": "Bearer " + token
                },
                contentType: "application/json",
                data: JSON.stringify(baguwen),
                success: function(response) {
                    if (response.code === 200) {
                        showToast("添加八股文成功", "success");
                        $("#addModal").modal("hide");
                        loadBaguwen();
                        // 刷新类型列表
                        loadBaguwenTypes();
                    } else {
                        showToast("添加八股文失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("添加八股文失败: " + xhr.responseJSON.message, "danger");
                }
            });
        }
        
        // 获取八股文详情
        function getBaguwen(id) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/baguwen/${id}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        const baguwen = response.data;
                        
                        // 填充详情模态框
                        $("#detailType").text(baguwen.type);
                        $("#detailQuestion").text(baguwen.question);
                        $("#detailContent").text(baguwen.content);
                        $("#detailCreateTime").text(formatDateTime(baguwen.createTime));
                        $("#detailUpdateTime").text(formatDateTime(baguwen.updateTime));
                        
                        // 设置收藏星标并检查是否已收藏
                        const favoriteStar = $("#detailFavoriteStar");
                        favoriteStar.data("id", baguwen.id);
                        
                        // 检查是否收藏
                        checkIsFavorite(baguwen.id, function(isFavorite) {
                            if (isFavorite) {
                                favoriteStar.removeClass("far").addClass("fas");
                                // 获取收藏信息
                                getFavoriteByBaguwenId(baguwen.id, function(favorite) {
                                    currentFavorite = favorite;
                                    // 显示备注区域
                                    $("#favoriteRemarkArea").removeClass("d-none");
                                    $("#favoriteRemark").text(favorite.remark || "暂无备注");
                                });
                            } else {
                                favoriteStar.removeClass("fas").addClass("far");
                                currentFavorite = null;
                                $("#favoriteRemarkArea").addClass("d-none");
                            }
                        });
                        
                        $("#detailModal").modal("show");
                    } else {
                        showToast("获取八股文详情失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("获取八股文详情失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 获取八股文用于编辑
        function editBaguwen(id) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/baguwen/${id}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        const baguwen = response.data;
                        // 填充编辑表单
                        $("#editId").val(baguwen.id);
                        $("#editType").val(baguwen.type);
                        $("#editQuestion").val(baguwen.question);
                        $("#editContent").val(baguwen.content);
                        
                        $("#editModal").modal("show");
                    } else {
                        showToast("获取八股文信息失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("获取八股文信息失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 更新八股文
        function updateBaguwen() {
            const id = $("#editId").val();
            const baguwen = {
                type: $("#editType").val(),
                question: $("#editQuestion").val(),
                content: $("#editContent").val()
            };
            
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/baguwen/${id}`,
                type: "PUT",
                headers: {
                    "Authorization": "Bearer " + token
                },
                contentType: "application/json",
                data: JSON.stringify(baguwen),
                success: function(response) {
                    if (response.code === 200) {
                        showToast("更新八股文成功", "success");
                        $("#editModal").modal("hide");
                        refreshCurrentPage();
                        // 如果更改了类型，刷新类型列表
                        loadBaguwenTypes();
                    } else {
                        showToast("更新八股文失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("更新八股文失败: " + xhr.responseJSON.message, "danger");
                }
            });
        }
        
        // 删除八股文
        function deleteBaguwen(id) {
            if (confirm("确定要删除这个八股文吗？")) {
                const token = localStorage.getItem('token');
                
                $.ajax({
                    url: `/api/baguwen/${id}`,
                    type: "DELETE",
                    headers: {
                        "Authorization": "Bearer " + token
                    },
                    success: function(response) {
                        if (response.code === 200) {
                            showToast("删除八股文成功", "success");
                            refreshCurrentPage();
                            // 刷新类型列表
                            loadBaguwenTypes();
                        } else {
                            showToast("删除八股文失败: " + response.message, "danger");
                        }
                    },
                    error: function(xhr) {
                        showToast("删除八股文失败: " + xhr.statusText, "danger");
                    }
                });
            }
        }
        
        // 渲染八股文列表
        function renderBaguwenList(pageResult) {
            const baguwenList = $("#baguwenList");
            baguwenList.empty();
            
            if (pageResult.list.length === 0) {
                baguwenList.append('<tr><td colspan="5" class="text-center">没有找到八股文</td></tr>');
                $("#totalCount").text(0);
                renderPagination(0);
                return;
            }
            
            pageResult.list.forEach(function(baguwen) {
                const row = $("<tr></tr>");
                row.append(`<td>${baguwen.id}</td>`);
                row.append(`<td>${baguwen.type}</td>`);
                row.append(`<td>${baguwen.question}</td>`);
                row.append(`<td>${truncateText(baguwen.content, 30)}</td>`);
                
                const actionCell = $("<td></td>");
                const actionGroup = $('<div class="btn-group btn-group-sm"></div>');
                
                // 查看按钮
                const viewBtn = $('<button class="btn btn-info">查看</button>');
                viewBtn.on("click", function() {
                    getBaguwen(baguwen.id);
                });
                
                // 编辑按钮
                const editBtn = $('<button class="btn btn-primary">编辑</button>');
                editBtn.on("click", function() {
                    editBaguwen(baguwen.id);
                });
                
                // 删除按钮
                const deleteBtn = $('<button class="btn btn-danger">删除</button>');
                deleteBtn.on("click", function() {
                    deleteBaguwen(baguwen.id);
                });
                
                // 收藏按钮
                const favoriteBtn = $('<button class="btn btn-warning"></button>');
                
                // 检查是否已收藏
                checkIsFavorite(baguwen.id, function(isFavorite) {
                    if (isFavorite) {
                        favoriteBtn.html('<i class="fas fa-star"></i>');
                        favoriteBtn.attr("title", "查看收藏");
                    } else {
                        favoriteBtn.html('<i class="far fa-star"></i>');
                        favoriteBtn.attr("title", "添加收藏");
                    }
                });
                
                favoriteBtn.on("click", function() {
                    const isStarred = $(this).find("i").hasClass("fas");
                    if (isStarred) {
                        // 已收藏，获取收藏信息
                        getFavoriteByBaguwenId(baguwen.id, function(favorite) {
                            // 打开编辑备注模态框
                            $("#favoriteId").val(favorite.id);
                            $("#favoriteBaguwenId").val(baguwen.id);
                            $("#favoriteRemarkInput").val(favorite.remark || "");
                            $("#favoriteModalLabel").text("编辑收藏备注");
                            $("#favoriteModal").modal("show");
                        });
                    } else {
                        // 未收藏，打开收藏模态框
                        $("#favoriteId").val("");
                        $("#favoriteBaguwenId").val(baguwen.id);
                        $("#favoriteRemarkInput").val("");
                        $("#favoriteModalLabel").text("添加收藏");
                        $("#favoriteModal").modal("show");
                    }
                });
                
                actionGroup.append(viewBtn);
                actionGroup.append(editBtn);
                actionGroup.append(deleteBtn);
                actionGroup.append(favoriteBtn);
                actionCell.append(actionGroup);
                
                row.append(actionCell);
                baguwenList.append(row);
            });
            
            $("#totalCount").text(pageResult.total);
            renderPagination(pageResult.total);
        }
        
        // 渲染分页
        function renderPagination(total) {
            const pagination = $("#pagination");
            pagination.empty();
            
            const totalPages = Math.ceil(total / pageSize);
            if (totalPages <= 1) return;
            
            // 上一页
            const prevLi = $('<li class="page-item"></li>');
            const prevLink = $('<a class="page-link" href="javascript:void(0)">上一页</a>');
            if (currentPage === 1) {
                prevLi.addClass("disabled");
            } else {
                prevLink.on("click", function() {
                    currentPage--;
                    refreshCurrentPage();
                });
            }
            prevLi.append(prevLink);
            pagination.append(prevLi);
            
            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, startPage + 4);
            
            for (let i = startPage; i <= endPage; i++) {
                const pageLi = $('<li class="page-item"></li>');
                if (i === currentPage) pageLi.addClass("active");
                
                const pageLink = $(`<a class="page-link" href="javascript:void(0)">${i}</a>`);
                pageLink.on("click", function() {
                    currentPage = i;
                    refreshCurrentPage();
                });
                
                pageLi.append(pageLink);
                pagination.append(pageLi);
            }
            
            // 下一页
            const nextLi = $('<li class="page-item"></li>');
            const nextLink = $('<a class="page-link" href="javascript:void(0)">下一页</a>');
            if (currentPage === totalPages) {
                nextLi.addClass("disabled");
            } else {
                nextLink.on("click", function() {
                    currentPage++;
                    refreshCurrentPage();
                });
            }
            nextLi.append(nextLink);
            pagination.append(nextLi);
        }
        
        // 刷新当前页
        function refreshCurrentPage() {
            if (currentSearchType === "all") {
                loadBaguwen();
            } else if (currentSearchType === "keyword") {
                searchBaguwen(currentSearchValue);
            } else if (currentSearchType === "type") {
                searchByType(currentSearchValue);
            }
        }
        
        // 显示提示框
        function showToast(message, type) {
            const toast = $(`
                <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000">
                    <div class="toast-header bg-${type} text-white">
                        <strong class="mr-auto">提示</strong>
                        <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="toast-body">${message}</div>
                </div>
            `);
            
            $("#toast").append(toast);
            toast.toast("show");
            
            // 自动删除
            setTimeout(function() {
                toast.remove();
            }, 3000);
        }
        
        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return "";
            const date = new Date(dateTimeStr);
            return date.toLocaleString("zh-CN");
        }
        
        // 截断文本
        function truncateText(text, length) {
            if (!text) return "";
            return text.length > length ? text.substring(0, length) + "..." : text;
        }
        
        // === 收藏相关功能 ===
        
        // 检查八股文是否已收藏
        function checkIsFavorite(baguwenId, callback) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/favorite/check/${baguwenId}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        callback(response.data);
                    } else {
                        callback(false);
                    }
                },
                error: function() {
                    callback(false);
                }
            });
        }
        
        // 获取八股文的收藏信息
        function getFavoriteByBaguwenId(baguwenId, callback) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/favorite/baguwen/${baguwenId}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        callback(response.data);
                    } else {
                        showToast("获取收藏信息失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 404) {
                        // 未收藏，不显示错误
                        callback(null);
                    } else {
                        showToast("获取收藏信息失败: " + xhr.statusText, "danger");
                    }
                }
            });
        }
        
        // 添加收藏
        function addFavorite(baguwenId, remark) {
            const favorite = {
                baguwenId: baguwenId,
                remark: remark
            };
            
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: "/api/favorite",
                type: "POST",
                headers: {
                    "Authorization": "Bearer " + token
                },
                contentType: "application/json",
                data: JSON.stringify(favorite),
                success: function(response) {
                    if (response.code === 200) {
                        showToast("添加收藏成功", "success");
                        $("#favoriteModal").modal("hide");
                        
                        // 如果是详情模态框中的收藏，更新星标
                        if ($("#detailModal").hasClass("show") && $("#detailFavoriteStar").data("id") == baguwenId) {
                            $("#detailFavoriteStar").removeClass("far").addClass("fas");
                            currentFavorite = response.data;
                            $("#favoriteRemarkArea").removeClass("d-none");
                            $("#favoriteRemark").text(remark || "暂无备注");
                        }
                        
                        // 刷新当前页面
                        refreshCurrentPage();
                    } else {
                        showToast("添加收藏失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("添加收藏失败: " + xhr.responseJSON.message, "danger");
                }
            });
        }
        
        // 更新收藏备注
        function updateFavorite(id, baguwenId, remark) {
            const favorite = {
                baguwenId: baguwenId,
                remark: remark
            };
            
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/favorite/${id}`,
                type: "PUT",
                headers: {
                    "Authorization": "Bearer " + token
                },
                contentType: "application/json",
                data: JSON.stringify(favorite),
                success: function(response) {
                    if (response.code === 200) {
                        showToast("更新收藏备注成功", "success");
                        $("#favoriteModal").modal("hide");
                        
                        // 如果是详情模态框中的收藏，更新备注
                        if ($("#detailModal").hasClass("show") && currentFavorite && currentFavorite.id == id) {
                            currentFavorite = response.data;
                            $("#favoriteRemark").text(remark || "暂无备注");
                        }
                        
                        // 刷新当前页面
                        refreshCurrentPage();
                    } else {
                        showToast("更新收藏备注失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("更新收藏备注失败: " + xhr.responseJSON.message, "danger");
                }
            });
        }
        
        // 取消收藏
        function deleteFavorite(id, baguwenId) {
            if (confirm("确定要取消收藏吗？")) {
                const token = localStorage.getItem('token');
                
                $.ajax({
                    url: `/api/favorite/${id}`,
                    type: "DELETE",
                    headers: {
                        "Authorization": "Bearer " + token
                    },
                    success: function(response) {
                        if (response.code === 200) {
                            showToast("取消收藏成功", "success");
                            
                            // 如果是详情模态框中的收藏，更新星标
                            if ($("#detailModal").hasClass("show") && $("#detailFavoriteStar").data("id") == baguwenId) {
                                $("#detailFavoriteStar").removeClass("fas").addClass("far");
                                currentFavorite = null;
                                $("#favoriteRemarkArea").addClass("d-none");
                            }
                            
                            // 刷新当前页面
                            refreshCurrentPage();
                            
                            // 如果是在收藏夹中，刷新收藏列表
                            if (isFavoriteView) {
                                loadFavorites();
                            }
                        } else {
                            showToast("取消收藏失败: " + response.message, "danger");
                        }
                    },
                    error: function(xhr) {
                        showToast("取消收藏失败: " + xhr.statusText, "danger");
                    }
                });
            }
        }
        
        // 加载收藏列表
        function loadFavorites() {
            isFavoriteView = true;
            
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: `/api/favorite?pageNum=${currentFavoritePage}&pageSize=${pageSize}`,
                type: "GET",
                headers: {
                    "Authorization": "Bearer " + token
                },
                success: function(response) {
                    if (response.code === 200) {
                        renderFavoriteList(response.data);
                    } else {
                        showToast("加载收藏列表失败: " + response.message, "danger");
                    }
                },
                error: function(xhr) {
                    showToast("加载收藏列表失败: " + xhr.statusText, "danger");
                }
            });
        }
        
        // 渲染收藏列表
        function renderFavoriteList(pageResult) {
            const favoriteList = $("#favoriteList");
            favoriteList.empty();
            
            if (pageResult.list.length === 0) {
                favoriteList.append('<tr><td colspan="6" class="text-center">收藏夹中没有八股文</td></tr>');
                $("#totalFavoriteCount").text(0);
                renderFavoritePagination(0);
                return;
            }
            
            pageResult.list.forEach(function(favorite) {
                const baguwen = favorite.baguwen;
                if (!baguwen) return;
                
                const row = $("<tr></tr>");
                row.append(`<td>${baguwen.id}</td>`);
                row.append(`<td>${baguwen.type}</td>`);
                row.append(`<td>${baguwen.question}</td>`);
                row.append(`<td>${truncateText(baguwen.content, 30)}</td>`);
                row.append(`<td>${truncateText(favorite.remark || "无", 20)}</td>`);
                
                const actionCell = $("<td></td>");
                const actionGroup = $('<div class="btn-group btn-group-sm"></div>');
                
                // 查看按钮
                const viewBtn = $('<button class="btn btn-info">查看</button>');
                viewBtn.on("click", function() {
                    getBaguwen(baguwen.id);
                });
                
                // 编辑备注按钮
                const editRemarkBtn = $('<button class="btn btn-primary">编辑备注</button>');
                editRemarkBtn.on("click", function() {
                    $("#favoriteId").val(favorite.id);
                    $("#favoriteBaguwenId").val(favorite.baguwenId);
                    $("#favoriteRemarkInput").val(favorite.remark || "");
                    $("#favoriteModalLabel").text("编辑收藏备注");
                    $("#favoriteModal").modal("show");
                });
                
                // 取消收藏按钮
                const unfavoriteBtn = $('<button class="btn btn-danger">取消收藏</button>');
                unfavoriteBtn.on("click", function() {
                    deleteFavorite(favorite.id, favorite.baguwenId);
                });
                
                actionGroup.append(viewBtn);
                actionGroup.append(editRemarkBtn);
                actionGroup.append(unfavoriteBtn);
                actionCell.append(actionGroup);
                
                row.append(actionCell);
                favoriteList.append(row);
            });
            
            $("#totalFavoriteCount").text(pageResult.total);
            renderFavoritePagination(pageResult.total);
        }
        
        // 渲染收藏分页
        function renderFavoritePagination(total) {
            const pagination = $("#favoritePagination");
            pagination.empty();
            
            const totalPages = Math.ceil(total / pageSize);
            if (totalPages <= 1) return;
            
            // 上一页
            const prevLi = $('<li class="page-item"></li>');
            const prevLink = $('<a class="page-link" href="javascript:void(0)">上一页</a>');
            if (currentFavoritePage === 1) {
                prevLi.addClass("disabled");
            } else {
                prevLink.on("click", function() {
                    currentFavoritePage--;
                    loadFavorites();
                });
            }
            prevLi.append(prevLink);
            pagination.append(prevLi);
            
            // 页码
            const startPage = Math.max(1, currentFavoritePage - 2);
            const endPage = Math.min(totalPages, startPage + 4);
            
            for (let i = startPage; i <= endPage; i++) {
                const pageLi = $('<li class="page-item"></li>');
                if (i === currentFavoritePage) pageLi.addClass("active");
                
                const pageLink = $(`<a class="page-link" href="javascript:void(0)">${i}</a>`);
                pageLink.on("click", function() {
                    currentFavoritePage = i;
                    loadFavorites();
                });
                
                pageLi.append(pageLink);
                pagination.append(pageLi);
            }
            
            // 下一页
            const nextLi = $('<li class="page-item"></li>');
            const nextLink = $('<a class="page-link" href="javascript:void(0)">下一页</a>');
            if (currentFavoritePage === totalPages) {
                nextLi.addClass("disabled");
            } else {
                nextLink.on("click", function() {
                    currentFavoritePage++;
                    loadFavorites();
                });
            }
            nextLi.append(nextLink);
            pagination.append(nextLi);
        }
        
        // 显示收藏夹视图
        function showFavorites() {
            // 隐藏主内容，显示收藏内容
            $("#mainContent").addClass("d-none");
            $("#favoriteContent").removeClass("d-none");
            
            // 更新标记
            isFavoriteView = true;
            
            // 加载收藏列表
            loadFavorites();
        }
        
        // 显示所有八股文（返回主视图）
        function showAllBaguwen() {
            // 显示主内容，隐藏收藏内容
            $("#mainContent").removeClass("d-none");
            $("#favoriteContent").addClass("d-none");
            
            // 更新标记
            isFavoriteView = false;
            
            // 加载八股文列表
            loadBaguwen();
        }
    </script>
</body>
</html> 